package design.donkey.auto.ddl.dialect.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import design.donkey.auto.ddl.dialect.mysql.handler.*;
import design.donkey.auto.ddl.model.TableMetaModel;
import lombok.extern.slf4j.Slf4j;

/**
 * MySql 8 方言实现
 *
 * @author zhangjiakung
 * @since 0.0.1
 */
@Slf4j
public class MySql8Dialect extends AbstractMySqlDialect {

    public MySql8Dialect() {
        super();
        columnHandlerList.add(new ColumnHandlerForJdbcType());
        columnHandlerList.add(new ColumnHandlerForUnsigned());
        columnHandlerList.add(new ColumnHandlerForZerofill());
        columnHandlerList.add(new ColumnHandlerNullable());
        columnHandlerList.add(new ColumnHandlerForDefaultAutoIncrement());
        columnHandlerList.add(new ColumnHandlerForComment());
    }

    @Override
    public String getProductVersion() {
        return "8";
    }

    @Override
    public String getCreateDdlByConnection(Connection connection, TableMetaModel tableMetaModel) {
        try (PreparedStatement preparedStatement =
            connection.prepareStatement("SHOW CREATE TABLE " + tableMetaModel.getName())) {
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                if (resultSet.next()) {
                    return resultSet.getString(2);
                }
                log.error("查询数据库中 {} 建表语句错误", tableMetaModel);
                return null;
            }
        } catch (Exception e) {
            log.debug("查询数据库中 {} 建表语句错误", tableMetaModel, e);
            return null;
        }
    }
}
